package org.korecky.gnotedigitalorganizer;

import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import net.miginfocom.swing.MigLayout;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.korecky.gnotedigitalorganizer.data.Book;
import org.korecky.gnotedigitalorganizer.data.Page;
import org.korecky.gnotedigitalorganizer.svg.DntToSvg;

public class ImportWindow extends JFrame {

    private JPanel contentPane;
    private JPanel panel;
    private JPanel pnlDevice;
    private JPanel pnlLibrary;
    private JLabel lblNewLabel;
    private JToolBar tlbDevice;
    private JToolBar tlbLibrary;
    private JTree treeDevice;
    private JTree treeLibrary;
    private JButton btnMoveToLibrary;
    private JButton btnNewFolderInLibrary;
    private JScrollPane scpDevice;
    private JScrollPane scpLibrary;
    private JPanel pnlDevicePreview;
    private JPanel pnlLibraryPreview;
    private JPanel panel_2;
    private JPanel panel_3;
    private JLabel lblNewLabel_1;
    private JLabel lblNewLabel_2;

    /**
     * Create the frame.
     */
    public ImportWindow(File deviceRootPath) {
	initComponents();

	if (deviceRootPath.exists()) {
	    List<Book> deviceBooks = DeviceManager.getBooksFromDevice(deviceRootPath);

	    // Display device books in GUI
	    DefaultMutableTreeNode deviceRootNode = new DefaultMutableTreeNode("G-Note device");
	    DefaultTreeModel deviceTreeModel = new DefaultTreeModel(deviceRootNode);
	    treeDevice.setRootVisible(false);
	    treeDevice.setModel(deviceTreeModel);

	    // Add all books to the tree model
	    for (Book book : deviceBooks) {
		DefaultMutableTreeNode newBookNode = new DefaultMutableTreeNode(book);
		deviceTreeModel.insertNodeInto(newBookNode, deviceRootNode, deviceRootNode.getChildCount());
	    }
	    treeDevice.expandPath(new TreePath(deviceRootNode.getPath()));
	}
	else {
	    dispose();
	}
    }

    private void initComponents() {
	setIconImage(Toolkit.getDefaultToolkit().getImage(ImportWindow.class.getResource("/org/korecky/gnotedigitalorganizer/resources/icons64x64/go-down.png")));
	setTitle("Import to the library");
	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	setBounds(100, 100, 868, 494);
	this.contentPane = new JPanel();
	this.contentPane.setBackground(Color.WHITE);
	this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
	setContentPane(this.contentPane);
	this.contentPane.setLayout(new MigLayout("", "[grow]", "[grow][]"));

	this.panel = new JPanel();
	this.panel.setBackground(Color.WHITE);
	this.contentPane.add(this.panel, "cell 0 0,grow");

	this.lblNewLabel_1 = new JLabel("Genius G-Note device");
	this.lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 12));
	this.lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);

	this.lblNewLabel_2 = new JLabel("Local library");
	this.lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 12));
	this.lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);

	this.panel_2 = new JPanel();
	this.panel_2.setBackground(Color.WHITE);
	this.panel_2.setBorder(new LineBorder(new Color(0, 0, 0)));

	this.scpDevice = new JScrollPane();
	this.scpDevice.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	this.scpDevice.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

	this.pnlDevicePreview = new JPanel();
	this.pnlDevicePreview.setBackground(Color.WHITE);
	this.scpDevice.setViewportView(this.pnlDevicePreview);
	this.pnlDevicePreview.setLayout(new BoxLayout(this.pnlDevicePreview, BoxLayout.Y_AXIS));

	this.pnlDevice = new JPanel();
	this.pnlDevice.setBackground(Color.WHITE);
	this.pnlDevice.setLayout(new MigLayout("", "[grow,fill]", "[][grow,fill]"));

	this.tlbDevice = new JToolBar();
	this.tlbDevice.setBackground(Color.WHITE);
	this.pnlDevice.add(this.tlbDevice, "cell 0 0");

	this.btnMoveToLibrary = new JButton("Move");
	this.btnMoveToLibrary.setBackground(Color.WHITE);
	this.btnMoveToLibrary.setIcon(new ImageIcon(ImportWindow.class.getResource("/org/korecky/gnotedigitalorganizer/resources/icons16x16/go-next.png")));
	this.tlbDevice.add(this.btnMoveToLibrary);

	this.treeDevice = new JTree();
	this.treeDevice.addTreeSelectionListener(new TreeSelectionListener() {
	    public void valueChanged(TreeSelectionEvent arg0) {
		treeDeviceValueChanged(arg0);
	    }
	});
	this.pnlDevice.add(this.treeDevice, "cell 0 1,grow");
	GroupLayout gl_panel_2 = new GroupLayout(this.panel_2);
	gl_panel_2.setHorizontalGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_2.createSequentialGroup().addGap(7).addComponent(this.scpDevice, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE).addGap(4).addComponent(this.pnlDevice, GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE).addContainerGap()));
	gl_panel_2.setVerticalGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_2.createSequentialGroup().addContainerGap().addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addComponent(this.scpDevice, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE).addComponent(this.pnlDevice, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)).addContainerGap()));
	this.panel_2.setLayout(gl_panel_2);

	this.panel_3 = new JPanel();
	this.panel_3.setBackground(Color.WHITE);
	this.panel_3.setBorder(new LineBorder(new Color(0, 0, 0)));

	this.pnlLibrary = new JPanel();
	this.pnlLibrary.setBackground(Color.WHITE);
	this.pnlLibrary.setLayout(new MigLayout("", "[grow,fill]", "[][grow]"));

	this.tlbLibrary = new JToolBar();
	this.tlbLibrary.setBackground(Color.WHITE);
	this.pnlLibrary.add(this.tlbLibrary, "cell 0 0");

	this.btnNewFolderInLibrary = new JButton("New Folder");
	this.btnNewFolderInLibrary.setBackground(Color.WHITE);
	this.btnNewFolderInLibrary.setIcon(new ImageIcon(ImportWindow.class.getResource("/org/korecky/gnotedigitalorganizer/resources/icons16x16/folder-new.png")));
	this.tlbLibrary.add(this.btnNewFolderInLibrary);

	this.treeLibrary = new JTree();
	this.pnlLibrary.add(this.treeLibrary, "cell 0 1,grow");

	this.scpLibrary = new JScrollPane();
	this.scpLibrary.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	this.scpLibrary.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

	this.pnlLibraryPreview = new JPanel();
	this.pnlLibraryPreview.setBackground(Color.WHITE);
	this.scpLibrary.setViewportView(this.pnlLibraryPreview);
	this.pnlLibraryPreview.setLayout(new BoxLayout(this.pnlLibraryPreview, BoxLayout.Y_AXIS));
	GroupLayout gl_panel_3 = new GroupLayout(this.panel_3);
	gl_panel_3.setHorizontalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING, gl_panel_3.createSequentialGroup().addContainerGap().addComponent(this.pnlLibrary, GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE).addPreferredGap(ComponentPlacement.RELATED).addComponent(this.scpLibrary, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE).addContainerGap()));
	gl_panel_3.setVerticalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_3.createSequentialGroup().addContainerGap().addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addComponent(this.scpLibrary, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE).addComponent(this.pnlLibrary, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)).addContainerGap()));
	this.panel_3.setLayout(gl_panel_3);
	GroupLayout gl_panel = new GroupLayout(this.panel);
	gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGap(7).addGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addComponent(this.lblNewLabel_1, GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE).addGap(4).addComponent(this.lblNewLabel_2, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)).addGroup(gl_panel.createSequentialGroup().addComponent(this.panel_2, GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE).addGap(4).addComponent(this.panel_3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))).addGap(7)));
	gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGap(7).addGroup(gl_panel.createParallelGroup(Alignment.LEADING).addComponent(this.lblNewLabel_1).addComponent(this.lblNewLabel_2)).addGap(4).addGroup(gl_panel.createParallelGroup(Alignment.LEADING).addComponent(this.panel_2, GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE).addComponent(this.panel_3, GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)).addGap(7)));
	this.panel.setLayout(gl_panel);

	this.lblNewLabel = new JLabel("Drag and Drop files books from left side (Genius G-Note device) to the right side (local library)");
	this.lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
	this.contentPane.add(this.lblNewLabel, "cell 0 1");
    }

    protected void treeDeviceValueChanged(TreeSelectionEvent evt) {
	TreePath selectedNodePath = treeDevice.getSelectionPath();
	DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedNodePath.getLastPathComponent();
	Book selectedBook = (Book) selectedNode.getUserObject();

	this.pnlDevicePreview.removeAll();

	for (Page page : selectedBook.getPages()) {
	    try {
		// DNT to SVG
		DntToSvg dntToSvg = new DntToSvg();
		String svgContent = dntToSvg.Convert(page.getUrl());

		// // Save to disk
		// File outputFile = new File("c:\\svg-test\\" + page.getTitle()
		// + ".svg");
		// OutputStream outputStream = new FileOutputStream(outputFile);
		// svgFileStream.writeTo(outputStream);
		// svgFileStream.flush();
		// outputStream.flush();
		// outputStream.close();

		// MyTranscoder transcoder = new MyTranscoder();
		// DOMImplementation impl =
		// SVGDOMImplementation.getDOMImplementation();
		// TranscodingHints hints = new TranscodingHints();
		// hints.put(ImageTranscoder.KEY_WIDTH, new Float(90));
		// hints.put(ImageTranscoder.KEY_HEIGHT, new Float(128));
		// hints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION,
		// ((SVGDOMImplementation) impl).getDOMImplementation());
		// hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
		// SVGConstants.SVG_NAMESPACE_URI);
		// hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
		// SVGConstants.SVG_NAMESPACE_URI);
		// hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT,
		// SVGConstants.SVG_SVG_TAG);
		// hints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, false);
		// transcoder.setTranscodingHints(hints);

		// To png
		PNGTranscoder transcoder = new PNGTranscoder();
		transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(128));
		transcoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(182));
		StringReader stringReader = new StringReader(svgContent);
		TranscoderInput transcoderInput = new TranscoderInput(stringReader);
		ByteArrayOutputStream pngFileStream = new ByteArrayOutputStream();
		TranscoderOutput transcodeOutput = new TranscoderOutput(pngFileStream);
		transcoder.transcode(transcoderInput, transcodeOutput);

		JLabel lblImagePreview = new JLabel("");
		this.pnlDevicePreview.add(lblImagePreview);
		lblImagePreview.setHorizontalAlignment(SwingConstants.CENTER);
		lblImagePreview.setBackground(Color.WHITE);
		lblImagePreview.setIcon(new ImageIcon(pngFileStream.toByteArray()));
		lblImagePreview.addMouseListener(new MouseAdapter() {
		    @Override
		    public void mouseClicked(MouseEvent e) {
			// DntFilePreviewWindow dntPreviewWindow = new
			// DntFilePreviewWindow();
		    }
		});

		// to pdf
		// PDFTranscoder pdf = new PDFTranscoder();
		// TranscoderInput pdfInput = new TranscoderInput(new
		// ByteArrayInputStream(svgFileStream.toByteArray()));
		// File pdfFile = new File("c:\\svg-test\\" + page.getTitle() +
		// ".pdf");
		// transcoderInput = new TranscoderInput(new
		// ByteArrayInputStream(svgFileStream.toByteArray()));
		// OutputStream pdfOutputStream = new FileOutputStream(pdfFile);
		// TranscoderOutput pdfTranscodeOutput = new
		// TranscoderOutput(pdfOutputStream);
		// pdf.transcode(transcoderInput, pdfTranscodeOutput);
	    }
	    catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	    }
	    catch (TranscoderException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	this.pnlDevicePreview.repaint();
    }
}
